﻿using System;
using System.IO;
using System.Web.UI.HtmlControls;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxUploadControl;
using NguyenHoa.Domains;
using NguyenHoa.Services;
using NguyenHoa.Web.App_Code;

namespace NguyenHoa.Web.Admin
{
  public partial class Advertisement : AdminBasePage
  {
    private string m_innerError = string.Empty;

    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.Advertisement;
      }
    }

    #region Events

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsCallback && !IsPostBack)
      {
        LoadAdvertisement();
      }
      if (gvAd.IsCallback)
        LoadAdvertisement();
    }

    protected void gvAd_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
    {
      string[] para = e.Parameters.Split('|');
      if (para[0] == "Save")
      {
        m_innerError = "Save|" + SaveAd();
      }
      else if (para[0] == "Delete")
      {
        int adId = 0;
        int.TryParse(para[1], out adId);
        m_innerError = DeleteAd(adId);
      }
      LoadAdvertisement();
    }

    protected void gvAd_CustomJSProperties(object sender, ASPxGridViewClientJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void uploader_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
    {
      string result = SavePostedFile(e.UploadedFile);
      if (result.IndexOf("ERROR") >= 0)
      {
        e.IsValid = false;
        e.ErrorText = string.Empty;
      }
      e.CallbackData = result;
    }

    protected void gvAd_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
    {
      if (e.DataColumn.FieldName != "IsShow") return;
      ASPxGridView grid = sender as ASPxGridView;
      HtmlInputCheckBox checkbox = grid.FindRowCellTemplateControl(e.VisibleIndex, e.DataColumn, "ckbShowLeft") as HtmlInputCheckBox;
      if (checkbox != null)
      {
        checkbox.Attributes.Add("onclick", "onShowLeftChecked('" + e.KeyValue + "', this.checked)");
      }
    }

    protected void ctrlCallback_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
    {
      string[] para = e.Parameter.Split('|');
      if (para[0] == "SaveQtt")
      {
        e.Result = SaveLeftAdvQtt();
      }
    }
    #endregion

    #region Methods

    private void LoadAdvertisement()
    {
      TList<Domains.Advertisement> adList = new AdvertisementService().GetByType(AdvertisementType.Advertisement, true);
      foreach (Domains.Advertisement ad in adList)
      {
        if (!string.IsNullOrEmpty(ad.ImagePath))
        {
          ad.ImagePath = "../" + ad.ImagePath;
        }
      }
      gvAd.DataSource = adList;
      gvAd.DataBind();

    }

    private string SaveLeftAdvQtt()
    {
      try
      {

      }
      catch (Exception ex)
      {
        WriteLog("Advertisements.aspx::Save Left Advertisement Qtt", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string SavePostedFile(UploadedFile uploadedFile)
    {
      string ret = "";
      string fileName = uploadedFile.FileName;
      string fileType = fileName.Substring(fileName.LastIndexOf("."));
      if (uploadedFile.IsValid)
      {
        try
        {
          string tempFileName = ((AdminBasePage)Page).CurrentUser.Username + "_" + Utils.GetDateTimeNumber(DateTime.Now) + fileType;
          fileName = MapPath(FolderDirector.TempFolder) + tempFileName;
          if (Session["TempUploadImage_Advertise"] != null)
          {
            File.Delete(Session["TempUploadImage_Advertise"].ToString());
          }
          uploadedFile.SaveAs(fileName);
          Session["TempUploadImage_Advertise"] = fileName;
          ret = tempFileName + "|" + tempFileName;
        }
        catch (Exception ex)
        {
          WriteLog("Advertisements.aspx::Save Posted File", ex);
          ret = "ERROR|" + Resources.Messages.ERR0004;
        }
      }
      return ret;
    }

    private string SaveAd()
    {
      try
      {
        AdvertisementService service = new AdvertisementService();
        Domains.Advertisement advertise;
        string website = Utils.FormatWebLink(txtWebsite.Text);
        string name = txtName.Text;
        int position = AdvertisementPosition.Left;
        if (cbxPosition.Value != null)
          int.TryParse(cbxPosition.Value.ToString(), out position);
        int advertiseId;
        int.TryParse(hfAdvertiseId.Value, out advertiseId);
        if (advertiseId > 0)
        {
          advertise = service.GetById(advertiseId);
          if (advertise == null) return Resources.Messages.ERR0003;
        }
        else
        {
          advertise = new Domains.Advertisement();
          advertise.Type = AdvertisementType.Advertisement;
        }
        advertise.Name = name;
        advertise.Website = website;
        advertise.IsShow = true;
        advertise.Position = position;

        if (Session["TempUploadImage_Advertise"] != null)
        {
          string error = Utils.SaveFileFromTemp(Session["TempUploadImage_Advertise"].ToString(), MapPath("../" + hfImagePath.Value));
          if (string.IsNullOrEmpty(error))
            advertise.ImagePath = hfImagePath.Value;
        }
        service.Save(advertise);
        //GlobalCache.Instance.Advertisement = null;
        Session["TempUploadImage_Advertise"] = null;
      }
      catch (Exception ex)
      {
        WriteLog("Advertisement.aspx::SaveAd", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string DeleteAd(int adId)
    {
      try
      {
        AdvertisementService service = new AdvertisementService();
        //Domains.ContactInfo advertise = service.GetById(adId);
        //if (advertise != null)
        //{
        //  string filePath = @MapPath("~\\" + advertise.ImagePath);
        //  Utils.DeleteFile(filePath);
        //}
        service.Delete(adId);
        //GlobalCache.Instance.Advertisement = null;
      }
      catch (Exception ex)
      {
        WriteLog("Advertisements.aspx::Delete Addvertisement", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }
    #endregion
  }
}
